<?php

namespace app\api\service\admin;

use app\common\library\Auth;
use think\Validate;
use think\Db;

class CourseService
{
    // 列表
    public static function index()
    {
        try {
            // 初始化安全的查询条件
            $where = [];

            // 分页查询
            $list = \app\admin\model\Course::where($where)
                ->field('course_id,course_name,color')
                ->order('weigh', 'asc')
                ->select();

            return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $list];
        } catch (\Exception $e) {
            // 记录日志并返回通用错误信息
            \think\facade\Log::error('Course index error: ' . $e->getMessage());
            return ['code' => 500, 'msg' => 'Server Error', 'state' => 'ERROR'];
        }
    }


    // 详情
    public static function detail($data)
    {
        $auth = Auth::instance();
        $course_id = $data['course_id'];
        $coures = \app\admin\model\Course::where('course_id', $course_id)->field('course_id,course_name,color')->find();

        $result['coures'] = $coures;
        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
    }

    public static function add($data)
    {
        $validate = new Validate([
            'course_name' => 'require',
            'color' => 'require',
        ], [
            'course_name.require' => 'Course name is not empty',
            'color.require' => 'Color is not empty',
        ]);
        // return $data['studio_id'];
        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        try {

            $result = \app\admin\model\Course::create($data);

            Db::commit();
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
    }

    public static function edit($data)
    {
        $validate = new Validate([
            'course_id' => 'require',
            'course_name' => 'require',
            'color' => 'require',
        ], [
            'course_id.require' => 'CourseId is not empty',
            'course_name.require' => 'Course name is not empty',
            'color.require' => 'Color is not empty',
        ]);
        // return $data['studio_id'];
        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        try {

            $result = \app\admin\model\Course::update($data);

            Db::commit();
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
    }


    public static function save($data)
    {
        $validate = new Validate([
            'course_name' => 'require',
            'color' => 'require',
            'course_id' => 'requireIf:update,true',
        ], [
            'course_name.require' => 'Course name is not empty',
            'color.require' => 'Color is not empty',
            'course_id.requireIf' => 'CourseId is required for update',
        ]);

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        Db::startTrans();  // 修改为正确的开启事务方法
        try {
            if(isset($data['course_id']) && $data['course_id']){
                $result = \app\admin\model\Course::update($data);
            }else{
                $result = \app\admin\model\Course::create($data);
            }
            Db::commit();
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database operation failed', 'state' => 'DATABASE_ERROR', 'data' => null];
        }
        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
    }



    // 删除
    public static function del($data)
    {
        // 验证$data['id']是否为空且为数字
        if (empty($data['course_id']) || !is_numeric($data['course_id'])) {
            return ['code'=>400, 'msg'=>'Invalid parameters', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务删除数据
        Db::startTrans();
        try {
            $result = \app\admin\model\Course::destroy($data['course_id']);

            if($result){
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database operation failed', 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }


    // 下拉查询
    public static function select()
    {
        try {
            $studio = \app\admin\model\Course::field('course_id,course_name')
                ->order('weigh', 'asc')
                ->select();

            if (empty($studio)) {
                return ['code' => 404, 'msg' => 'No data found', 'state' => 'EMPTY', 'data' => []];
            }

            return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $studio];
        } catch (\Exception $e) {
            return ['code' => 500, 'msg' => 'Database error', 'state' => 'ERROR', 'data' => []];
        }
    }



}
